package com.disk.controller;

import com.disk.domain.User;
import com.disk.handleResult.Result;
import com.disk.service.LoginService;
import com.disk.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    @Operation(summary = "security登录认证")
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        return loginService.login(user);
    }

    @Operation(summary = "通过Authentication获取" +
            "JwtAuthenticationTokenFilter中设置好的principal:userLoginDetail.getUser().getId()")
    @GetMapping("/get")
    public Object getCurrentUserName(Authentication authentication){
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    @Operation(summary = "通过登录时的用户名查询角色id")
    @GetMapping("/role")
    public Object getRoleByUserName(@RequestParam("username") String username){
        User user = userService.getByName(username);
        return userService.getRoleByUserId(user.getId());
    }

    @Operation(summary = "登出")
    @GetMapping("/logout")
    public Result logout(){
        return loginService.logout();
    }

    @Operation(summary = "仅支持用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        return userService.register(user);
    }
}
